package com.example.amoocspringboot.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    // 有效期为1小时
    public static final Long JWT_TTL = 60 * 60 * 1000L;
    // 加密使用的key
    public static final String JWT_KEY = "this_key_is_create_by_jerry_at_2022-7-5_you_can_replace_by_yourself_but_must_be_long" + "_otherwise_will_throw_a_exception";

    public static String createToken(String id, String subject) {
        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes(StandardCharsets.UTF_8));
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(claims).setSubject(subject).setExpiration(new Date(System.currentTimeMillis() + JWT_TTL)).signWith(key, SignatureAlgorithm.HS256);
        return jwtBuilder.compact();
    }

    public static Claims parseToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes(StandardCharsets.UTF_8));
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }
}